import threading
import utils
import random
from login import use_default_login
import tasks
import requests
from urllib3.exceptions import InsecureRequestWarning

# 禁用安全请求警告
requests.urllib3.disable_warnings(InsecureRequestWarning)


class WeChatInfrastructureEditor(utils.WeChatClient):

    def delete_power(self):
        header = {
            "Referer": "https://mp.weixin.qq.com/cgi-bin/component_unauthorize?action=id&t=service/auth_profile"
                       "&component_appid=wx1b5b1f78a865bf21&token={0}&lang=zh_CN".format(self.token)
        }
        resp = self.session.post(
                        '{0}/cgi-bin/component_unauthorize'.format(self.url),
                {
                    'token': self.token,
                    'lang': 'zh_CN',
                    'f': 'json',
                    'ajax': '1',
                    'random': random.random(),
                    'component_appid': 'wx1b5b1f78a865bf21'
                }, headers=header)
        try:
            data = resp.json()
            if data['base_resp']['ret'] == 0:
                self.log_line('删除兔微米授权功能设置成功')
                return True
            else:
                self.log_err('错误: ' + data['base_resp']['err_msg'])
                return False
        except:
            print(resp.content)
            self.log_err('删除兔微米授权功能设置失败')
            return False


class EditorThread(threading.Thread):
    def __init__(self, service, task):
        threading.Thread.__init__(self)
        self.service = service
        self.task = task

    def run(self):
        c = WeChatInfrastructureEditor(srv)
        try:
            if not c.enter(self.task['gh_id']):
                return
            c.delete_power()
        except ConnectionError:
            pass


if __name__ == '__main__':
    m = tasks.default_manager()
    srv = use_default_login()
    chunks = m.get_task_chunks(5)
    total_chunks = len(chunks)
    current_chunk = 1
    for chunk in chunks:
        print('=第{}批线程开始='.format(current_chunk))
        pool = []
        for task_item in chunk:
            thread = EditorThread(srv, task_item)
            thread.start()
            pool.append(thread)
        for thread in pool:
            thread.join()
        print('=第{}/{}批线程结束='.format(current_chunk, total_chunks))
        current_chunk += 1
    input('运行完毕，然回车键退出')